import Common
from DBaseUtil import DBase
from UsersDBUtil import UsersDB

class TimeOut:
    
    TimeOut_Threshold = 10
    
    UserPackets_TABLE = "user_packets"
    
    User_FIELD = "user"
    Time_FIELD = "time"
    
    def __init__(self):
        self.db = DBase("timeout.db", self.scriptCreateTimeOutDB())
                    
    def HandleTimeOut(self, user):
        if self.UserExists(user) is False:      # find if first time user
            return
        else:
            currentTime = Common.GetCurrentTime()
            lastPacketTime = self.GetLastRequestTime(user)
#            Common.getLogger.logthis("Last Packet time: " + str(lastPacketTime) + " and currentTime: " + str(currentTime), Common.Logger.GET_Request)
#            if lastPacketTime == 0:
#                self.db.UpdateRequestTime(user, currentTime)
#                return None
            if currentTime - lastPacketTime > self.TimeOut_Threshold:
                Common.getLogger.logthis("Current access time:  " + str(currentTime) , Common.Logger.GET_Request)
                Common.getLogger.logthis("User last accessed at " + str(lastPacketTime), Common.Logger.GET_Request)
                Common.getLogger.logthis("User timed out in DB. Deleting " + user + " from db !!!!!!!!!!!!!! \n\n", Common.Logger.GET_Request)
                self.DeleteUser(user)
            self.UpdateRequestTime(user, currentTime)
            
    def DeleteUser(self, user):
        userDB = UsersDB(user)
        userDB.DeleteDB()
    
    def UpdateRequestTime(self, user, currentTime):
        self.db.cursor.execute("UPDATE " + TimeOut.UserPackets_TABLE + " \
        SET " + TimeOut.Time_FIELD + " = \"%s\" " % (str(currentTime)) + " \
        WHERE " + TimeOut.User_FIELD + " = \"%s\" " % (user))
    
    def UserExists(self, user):        
        self.db.cursor.execute("SELECT " + TimeOut.User_FIELD + "\
        FROM " + TimeOut.UserPackets_TABLE + " \
        WHERE " + TimeOut.User_FIELD + " = \"%s\" "% (user))
        self.db.row = self.db.cursor.fetchone()
        
        userFound = True if (self.db.row is not None) else False
        
        if not userFound:
            self.db.cursor.execute("INSERT INTO " + TimeOut.UserPackets_TABLE + " \
            (" + TimeOut.User_FIELD + ", " + TimeOut.Time_FIELD + ")\
            VALUES (\"%s\", \"%s\")" % (user, Common.GetCurrentTime() ))
        
        return userFound
    
    def GetLastRequestTime(self, user):
        self.db.cursor.execute("SELECT "+ TimeOut.Time_FIELD+" FROM " + TimeOut.UserPackets_TABLE + "\
        WHERE " + TimeOut.User_FIELD + "= ?", [user])
        self.db.row = self.db.cursor.fetchone()
                
        packetTime = self.db.row[0]
        return float(packetTime)
    
    def scriptCreateTimeOutDB(self):
        return "CREATE TABLE IF NOT EXISTS " + TimeOut.UserPackets_TABLE + " ( \
         " + TimeOut.User_FIELD + " TEXT PRIMARY KEY, \
         " + TimeOut.Time_FIELD + " TEXT NOT NULL);"